﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Asoft.Web.Controllers
{
    public static class AsoftControllExtension
    {
        static T GetRequestValue<T>(System.Web.Mvc.Controller controller, string key, T defaultValue)
        {
            var str = controller.Request[key];
            if (string.IsNullOrEmpty(str))
            {
                return defaultValue;
            }
            return (T)System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(str);
        }

        static string GetRequestString(System.Web.Mvc.Controller controller, string key)
        {
            return controller.Request[key];
        }

        public static string JQGridSearch(this System.Web.Mvc.Controller controller)
        {
            return GetRequestValue(controller, "_search", "");
        }

        public static int JQGridRows(this System.Web.Mvc.Controller controller)
        {
            return GetRequestValue(controller, "rows", 1);
        }


        public static int JQGridPage(this System.Web.Mvc.Controller controller)
        {
            return GetRequestValue(controller, "page", 1);
        }

        public static string JQGridSidx(this System.Web.Mvc.Controller controller)
        {
            return GetRequestValue(controller, "sidx", "");
        }

        public static string JQGridSord(this System.Web.Mvc.Controller controller)
        {
            return GetRequestValue(controller, "sord", "");
        }

        //        [2]: "oper"
        //[3]: "id"

        public static int JQGridEditId(this System.Web.Mvc.Controller controller)
        {
            if (JQGridOper(controller) == EOper.Add)
            {
                return 0;
            }
            return GetRequestValue(controller, "id", 0);
        }

        public static EOper JQGridOper(this System.Web.Mvc.Controller controller)
        {
            return GetRequestValue(controller, "oper", EOper.Add);
        }
    }
}